<template>
  <article class="media">
    <div class="media-content">
      <form @submit.prevent="onSubmit">
        <b-field>
          <b-input v-model.lazy="commentText" :disabled="isLoading" maxlength="400" placeholder="Add a comment..."
                   type="textarea"></b-input>
        </b-field>
        <nav class="level">
          <div class="level-left">
            <b-button :disabled="isLoading" class="level-item" native-type="submit" type="is-primary">
              Comment
            </b-button>
          </div>
        </nav>
      </form>
    </div>
  </article>
</template>

<script>
import {pushComment} from '@/api/comment'
import axios from 'axios'

export default {
  name: 'LvCommentsForm',
  data() {
    return {
      commentText: '',
      isLoading: false
    }
  },
  props: {
    slug: {
      type: String,
      default: null
    }
  },
  methods: {
    // async checkShieldWords() {
    //   const { data } = await this.$axios.get('/api/comment/check', {
    //     params: {
    //       commentText: this.commentText,
    //     }
    //   })
    //   if (data) {
    //     console.log(data);
    //     return this.isLoading = true
    //   } else {
    //     this.$message.error('评论内容包含敏感词汇，请修改后重新提交！')
    //     return this.isLoading = false
    //   }
    // },
    async onSubmit() {
      try {
        let postData = {}
        // console.log(this.commentText)
        const {data} = await axios.get('/comment/check', {
          params: {
            commentText: decodeURIComponent(this.commentText),
          }
        })
        this.commentText = data
        postData['content'] = this.commentText
        postData['topic_id'] = this.slug
        console.log(data);
        this.isLoading = true
        await pushComment(postData)
        this.$emit('loadComments', this.slug)
        this.$emit('submitComment', this.commentText)
        this.commentText = ''
        // console.log(this.isLoading);
      } catch (e) {
        this.$buefy.toast.open({
          message: `Cannot comment this story. ${e}`,
          type: 'is-danger'
        })
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>
